package ru.voice2blog.uploader.ftp;

import org.apache.commons.net.ftp.FTPClient;
import ru.voice2blog.common.V2BServiceAdapter;
import ru.voice2blog.common.exception.PrepareException;
import ru.voice2blog.common.exception.UploadException;
import ru.voice2blog.common.uploader.DataUploader;
import ru.voice2blog.common.uploader.UploadResult;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


/**
 * User: ilya.ufo
 * Date: 08.03.11
 * Time: 20:21
 */
public class FtpUploader extends V2BServiceAdapter implements DataUploader {

    private String ftpLogin;
    private String ftpPassword;
    private String ftpAddress;
    private String ftpPath;
    private static FTPClient ftpClient;


//    public static void main(String[] args ) throws PrepareException {
//        DataUploader uploader = new FtpUploader();
//        uploader.init(null);
//        uploader.prepare();
//        uploader.upload(new File("C://setup.log"));
//        uploader.destroy();
//    }

    public void prepare(Properties props) throws PrepareException {
        try {
            ftpClient.connect(ftpAddress);
            ftpClient.login(ftpLogin, ftpPassword);
        } catch (IOException e) {
            throw new PrepareException("Couldn't connect or login to " + ftpAddress, e);
        }
    }

    public void clean() {
        try {
            ftpClient.logout();
            ftpClient.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public UploadResult upload(File file) throws UploadException {
        try {
            InputStream is = new FileInputStream(file);
            String filename = file.getName();
            boolean isOk = ftpClient.storeFile(ftpPath + filename, is);
            return isOk ? new UploadResult(isOk, "http://" + ftpAddress + "/" + ftpPath + filename) : null;
        } catch (Exception e) {
            throw new UploadException("Error on uploading to ftp server.", e);
        }
    }


    public void init(Properties properties) {
        ftpAddress = properties.getProperty("ftpAddress");
        ftpLogin = properties.getProperty("ftpLogin");
        ftpPassword = properties.getProperty("ftpPassword");
        ftpPath = properties.getProperty("ftpPath");

        ftpClient = new FTPClient();
    }
}
